#include "log.h"
#include <stdio.h>

/*
[formats]
default="%-6V|%d(%F %T.%l)|%f:%L|# %m%n"
[rules]
xx.DEBUG    >stdout; default
xx.INFO     "./logs/%c_%d(%F).log",5M; default
*/
static const char * _cfg_prefix = R"([formats]
default="%-6V|%d(%F %T.%l)|%f:%L|# %m%n"
[rules]
xx.DEBUG    >stdout; default
xx.INFO     )";
static const char * _cfg_suffix = "/%c_%d(%F).log\"; default\n";

zlog_category_t *_zlog = NULL;
// 在dir目录下每天创建一个以xx_20231201.log规则命名的日志文件,最大5M
// 保存30天的数据
int xx_init_logger(const char * dir, int max_cnt)
{
    char buffer[128] = {0};
    FILE *pf = NULL;
    // 创建日志目录
    sprintf(buffer, "mkdir -p %s", dir);
    pf = popen(buffer, "r");    
    if (pf == NULL) {
        printf("mkdir log dir err\n");
        return -1;
    }
    pclose(pf);
    //删除30天前的日志
    sprintf(buffer, "find %s -type f -name \"*.log\" -mtime +%d -exec rm {} \\;", dir, max_cnt);
    pf = popen(buffer, "r");    
    if (pf == NULL) {
        printf("rm old log err\n");
        return -2;
    }
    pclose(pf);

    //get cfg string
    char cfg_str[256] = {0};
    sprintf(cfg_str, "%s\"%s%s", _cfg_prefix, dir, _cfg_suffix);
    // printf("xx log cfg:\n%s",cfg_str);

    int rc;

	rc = zlog_init_from_string(cfg_str);
	if (rc) {
		printf("init failed\n");
		return -3;
	}

    //这个参数指定类型伴随配置文件
	_zlog = zlog_get_category("xx");
	if (!_zlog) {
		printf("get cat fail\n");
		zlog_fini();
		return -4;
	}
    return 0;
}

void xx_deinit_logger(void){
    zlog_fini();
}
